package com.yiren.manager.ctrl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yiren.core.exception.MyException;
import com.yiren.core.utils.ResourceUtil;
import com.yiren.manager.utils.HTTPResult;
import com.yiren.manager.utils.HTTPStatusCode;

/**
 * @author 
 */
@ControllerAdvice
public class GlobalExceptionAdvice {

	/**
	 * 处理自定义异常
	 * 
	 * @param request
	 * @param ex
	 * @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @return
	 */
	@ExceptionHandler(MyException.class)
	@ResponseBody
	public HTTPResult handleyirenException(HttpServletRequest request, MyException ex) {
		HTTPResult result = new HTTPResult();
		result.setCode(HTTPStatusCode.Error.value());

		if (ex.getMessages().getMessages().size() == 0) {
			String msg = ex.getMessage();
			String info = ResourceUtil.getString(msg).isEmpty()?msg: ResourceUtil.getString(msg);
			result.setInfo(info);
			System.out.println("handleMyException:"+info);
		}else{
			result.setInfo(ex.getMessage());
		}
		return result;
	}

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public HTTPResult handleException(HttpServletRequest request, Exception ex) {
		HTTPResult result = new HTTPResult();
		result.setCode(HTTPStatusCode.Error.value());

		String info = ex.getMessage();
		ex.printStackTrace();
		result.setInfo(info);
		System.out.println("handleException:"+info);
		return result;
	}
}
